package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.bo.SpuBo;
import com.leyou.item.mapper.*;
import com.leyou.item.pojo.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    static final Logger logger = LoggerFactory.getLogger(GoodsService.class);

    public PageResult<SpuBo> querySpuByPage(String key, Boolean saleable, Integer page, Integer rows) {
        //1.查询SPU
        //分页，最多允许查100条
        PageHelper.startPage(page,Math.min(rows,100));

        //创建查询条件
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();

        //是否过滤上下架
        if (saleable !=null ){
            criteria.orEqualTo("saleable",saleable);
        }
        //是否模糊查询

        if (StringUtils.isNotBlank(key)){
            criteria.andLike("title","%"+key+"%");
        }
        Page<Spu> pageInfo = (Page<Spu>) this.spuMapper.selectByExample(example);

        List<SpuBo> list = pageInfo.getResult().stream().map(
                spu -> {
                    //把spu 变为 spuBo
                    SpuBo spuBo = new SpuBo();
                    //属性拷贝
                    BeanUtils.copyProperties(spu,spuBo);

                    //2.查询spu的商品分类命长，要查三级分类
                    List<String> names = this.categoryService.queryNamesByIds(Arrays.asList(spu.getCid1(),spu.getCid2(),spu.getCid3()));
                    //将分类名称拼接后存入
                    spuBo.setCname(StringUtils.join(names,"/"));

                    //3.查询spu的品牌名称
                    Brand brand = this.brandMapper.selectByPrimaryKey(spu.getBrandId());
                    spuBo.setBname(brand.getName());
                    return spuBo;
                }).collect(Collectors.toList());

        return new PageResult<>(pageInfo.getTotal(),list);
    }


    @Transactional
    public void saveGoods(SpuBo spu) {

        //保存spu
        spu.setSaleable(true);
        spu.setValid(true);
        spu.setCreateTime(new Date());
        spu.setLastUpdateTime(spu.getCreateTime());
        this.spuMapper.insert(spu);

        //保存spu子表
        spu.getSpuDetail().setSpuId(spu.getId());
        this.spuDetailMapper.insert(spu.getSpuDetail());

        //保存sku
        List<Sku> skus = spu.getSkus();
        
        skus.forEach(sku -> {
            sku.setSpuId(spu.getId());
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(sku.getCreateTime());
            this.skuMapper.insert(sku);


            //保存库存信息
            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());
            this.stockMapper.insert(stock);
        });

        this.sendMessage(spu.getId(),"insert");

    }

    public SpuDetail querySpuDetailById(Long pid) {
        return this.spuDetailMapper.selectByPrimaryKey(pid);
    }

    public List<Sku> querySkuBySpuId(Long id) {

        Sku record = new Sku();
        record.setSpuId(id);
        List<Sku> skus = this.skuMapper.select(record);

        skus.forEach(sku -> {
            sku.setStock( this.stockMapper.selectByPrimaryKey(sku.getId()).getStock());
        });
        return skus;
    }

    @Transactional
    public void saveupdateGoods(SpuBo spu) {
        //更改spu
        spu.setLastUpdateTime(new Date());
        this.spuMapper.updateByPrimaryKeySelective(spu);

        //更改spuDetail
        this.spuDetailMapper.updateByPrimaryKeySelective(spu.getSpuDetail());

        List<Sku> skus = spu.getSkus();

        Sku record = new Sku();
        record.setSpuId(spu.getId());
        List<Sku> oldSku = this.skuMapper.select(record);

        skus.forEach(sku -> {
            if (sku.getId() == null){
                //先保存spk
                sku.setSpuId(spu.getId());
                sku.setCreateTime(new Date());
                sku.setLastUpdateTime(sku.getCreateTime());
                this.skuMapper.insert(sku);
                //保存库存信息
                Stock stock = new Stock();
                stock.setSkuId(sku.getId());
                stock.setStock(sku.getStock());
                this.stockMapper.insertSelective(stock);
            }else {
                //修改sku
                sku.setLastUpdateTime(new Date());
                this.skuMapper.updateByPrimaryKeySelective(sku);
                //修改库存信息
                Stock stock = new Stock();
                stock.setSkuId(sku.getId());
                stock.setStock(sku.getStock());
                this.stockMapper.updateByPrimaryKeySelective(stock);
            }

            oldSku.removeIf(oldsku->oldsku.getId().longValue() == sku.getId().longValue());
        });

        if (0!=oldSku.size()){
            oldSku.forEach(oldsku->{
                //下架
                oldsku.setEnable(false);
                oldsku.setLastUpdateTime(new Date());
                this.skuMapper.updateByPrimaryKeySelective(oldsku);
                //修改库存信息
                Stock stock = new Stock();
                stock.setSkuId(oldsku.getId());
                stock.setStock(oldsku.getStock());
                this.stockMapper.updateByPrimaryKeySelective(stock);
            });
        }

        this.sendMessage(spu.getId(),"update");

    }

    public Spu querySpuById(Long id) {
       return this.spuMapper.selectByPrimaryKey(id);
    }




    private void sendMessage(Long id, String type){
        // 发送消息
        try {
            this.amqpTemplate.convertAndSend("item." + type, id);
        } catch (Exception e) {
            logger.error("{}商品消息发送异常，商品id：{}", type, id, e);
        }
    }

    public Sku querySkuById(Long id) {
        return this.skuMapper.selectByPrimaryKey(id);
    }
}
